package com.devunion.bogdan.view.editors;

import com.devunion.bogdan.model.project.Annotation;
import com.devunion.bogdan.view.editors.event.SelectionListener;

import javax.swing.*;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.util.List;

/**
 * @author Viktar Liaskovich
 */
public class AnnotationEditor extends JTextArea {
    private boolean skipUpdate = false;

    public AnnotationEditor() {
        setEnabled(false);

        getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                updateText(getText());
            }

            public void removeUpdate(DocumentEvent e) {
                updateText(getText());
            }

            public void changedUpdate(DocumentEvent e) {
                updateText(getText());
            }
        });

        final SelectionManager selectionManager = AnnotationManager.getInstance().getSelectionManager();

        selectionManager.addSelectionListener(new SelectionListener() {
            public void onSelectionChange(Component c, boolean selection) {
                List<Component> components = selectionManager.getSelectedComponents();
                boolean isCorrectSelection = components.size() == 1;

                setEnabled(isCorrectSelection);

                if (isCorrectSelection) {
                    Annotation annotation = ((AnnotationView) components.get(0)).getAnnotation();
                    setText(annotation.getText());
                } else {
                    clear();
                }
            }

            public void onSelectionAllChange(boolean selection) {
                clear();
                setEnabled(selection);
            }
        });
    }

    public void clear() {
        try {
            skipUpdate = true;

            setText("");
        } finally {
            skipUpdate = false;
        }
    }

    private void updateText(String newText) {
        if (skipUpdate) {
            return;
        }

        List<Component> list = AnnotationManager.getInstance().getSelectionManager().getSelectedComponents();

        assert list.size() == 1 : "We can edit annotation for one component only";

        Annotation annotation = ((AnnotationView) list.get(0)).getAnnotation();
        annotation.setText(newText);
    }
}
